import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:myapp/state/bluetooth.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:myapp/page/address/address.dart';
import 'package:myapp/page/bluetooth/index.dart';
import 'package:myapp/page/previewFile/previewFile.dart';
import 'package:myapp/state/notifications.dart';
import 'package:myapp/page/huaweiScan/huaweiScan.dart';

void handleWebMessage(Map data, WebViewController controller, BuildContext context) async {
  String methodName = data['method'];
  String callbackName = data['callbackName'];
  Map params = {};
  if (data['params'] is Map) {
    params.addAll(data['params']);
  }

  Map methods = allMethods();

  if (methods.containsKey(methodName)) {
    try{
     await methods[methodName](
        runJSFunction: (String fn, [e = '']) {
          String jsonString = jsonEncode(e);
          controller.runJavaScript('''
            if (window.$callbackName.$fn) {
              const info = JSON.parse('$jsonString')
              window.$callbackName.$fn(info)
            }
            if (window.$callbackName.onComplete) window.$callbackName.onComplete()
            delete window.$callbackName
         ''');
        },
       params : params,
       context: context
      );
    } catch(e) {
      debugPrint('err------->>>>>>>>>>$e');
      controller.runJavaScript('delete window.$callbackName');
    }

  } else {
    controller.runJavaScript('''
      if (window.$callbackName) delete window.$callbackName
    ''');
  }
}

// 扫码
void _scanCode({ runJSFunction, Map? params, required BuildContext context }) async {
  if (Platform.isAndroid) {
    debugPrint('当前是 Android');
  } else if (Platform.isIOS) {
    debugPrint('当前是 iOS');
  }
  final String? scanCode = await Navigator.push(context,MaterialPageRoute(builder: (context) => const HuaweiScan()));
  if (scanCode!.isEmpty) {
    runJSFunction('onError', {
      'type': 'err',
      'info': '当前用户没有扫描！'
    });
  } else {
    runJSFunction('onSuccess', {
      'type': 'success',
      'info': scanCode.replaceAll('\n', '')
    });
  }
}

// 跳转原生页面
void _changeSetting ({ runJSFunction, Map? params, required BuildContext context }) async {
  Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const Address()));
  runJSFunction('onSuccess', { 'type': 'success' });
}

void showAlert(String title, VoidCallback callBack, BuildContext context) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text('提示', style: TextStyle(fontSize: 20)),
        content: Text(title),
        actions: [
          TextButton(
            onPressed: callBack,
            child: const Text('确认'),
          )
        ],
      );
    },
  );
}

// 蓝牙写入
void _blueWire({ runJSFunction, Map? params, required BuildContext context }) async {
  try {
    var bytes = base64.decode(params!['info']);
    await context.read<BluetoothStore>().sendDataInChunks(bytes, 20);
    runJSFunction('onSuccess', { 'type': 'success' });
  } catch(err) {
    debugPrint('err-----------$err');
    runJSFunction('onError', { 'type': err });

    showAlert('打印机未连接，是否前往蓝牙配对页面？', (){
      Navigator.of(context).pop();
      Navigator.push(context, MaterialPageRoute(builder: (context) => const Bluetooth()));
    }, context);

  }
}

_setBlueTool({ runJSFunction, Map? params, required BuildContext context }){
  Navigator.push(context, MaterialPageRoute(builder: (context) => const Bluetooth()));
  runJSFunction('onSuccess', { 'type': 'success' });
}

// 查询状态栏高度
void _getStatusTop({ runJSFunction, Map? params, required BuildContext context }) {
  num statusTop = MediaQuery.of(context).padding.top;
  runJSFunction('onSuccess', { 'type': 'success', 'info' : statusTop });
}

// 查询蓝牙状态
void _blueIsConnectd({ runJSFunction, Map? params, required BuildContext context }) async {
  bool blueStatus = await context.read<BluetoothStore>().connectStatus();
  runJSFunction('onSuccess', { 'type': 'success', 'info' : blueStatus });
}

// 预览PDF
void _preview({ runJSFunction, Map? params, required BuildContext context }) {
  try {
    String fileUrl = params!['url'];
    Navigator.push(context, MaterialPageRoute(builder: (context) => PreviewFile(fileUrl: fileUrl)));
    runJSFunction('onSuccess', { 'type': 'success' });
  } catch(err) {
    debugPrint('err-----------$err');
    runJSFunction('onError', { 'type': err });
  }
}

// 消息发送
void _sendMessage({ runJSFunction, Map? params, required BuildContext context }) {
  try {
    var id = params!['id'];
    String title = params['title'];
    String  content = params['content'];
    var payload = params['payload'];
    context.read<NotificationsStore>().sendMessage(id, title, content, payload);
    runJSFunction('onSuccess', { 'type': 'success' });
  } catch(err) {
    debugPrint('err-----------$err');
    runJSFunction('onError', { 'type': err });
  }
}


Map allMethods () {
  return {
    'ScanCode': _scanCode,
    'ChangeSetting': _changeSetting,
    'BlueWire': _blueWire,
    'SetBlueTool': _setBlueTool,
    'GetStatusTop': _getStatusTop,
    'BlueIsConnectd': _blueIsConnectd,
    'Preview': _preview,
    'SendMessage': _sendMessage
  };
}
